"""Realtime statistics API endpoints."""

from __future__ import annotations

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.api.deps import get_current_user, get_db
from app.models.user import User
from app.schemas.statistics import (
    AggregatedStats,
    CurrentValue,
    DeviceSummary,
    MetricDistribution,
)
from app.services.statistics_service import StatisticsService

router = APIRouter()


@router.get("/current", response_model=list[CurrentValue])
def get_current_values(
    device_id: int | None = Query(None, description="Filter by device ID"),
    metric_names: list[str] | None = Query(None, description="Filter by metric names"),
    session: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> list[CurrentValue]:
    """Get current (latest) values for metrics.

    Returns the most recent reading for each metric, optionally
    filtered by device ID and/or metric names.

    Examples:
    - All current values: GET /statistics/current
    - Device 1: GET /statistics/current?device_id=1
    - Specific metrics: GET /statistics/current?metric_names=temperature&metric_names=pressure
    """
    service = StatisticsService(session)
    results = service.get_current_values(device_id=device_id, metric_names=metric_names)

    return [CurrentValue(**result) for result in results]


@router.get("/aggregated/{device_id}/{metric_name}", response_model=AggregatedStats)
def get_aggregated_stats(
    device_id: int,
    metric_name: str,
    hours: int = Query(1, ge=1, le=720, description="Time window in hours (max 30 days)"),
    session: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> AggregatedStats:
    """Get aggregated statistics for a metric over time window.

    Returns min, max, avg, count for the specified metric and time range.
    Useful for quick summary of metric behavior.

    Example: GET /statistics/aggregated/1/temperature?hours=24
    """
    service = StatisticsService(session)
    result = service.get_aggregated_stats(device_id=device_id, metric_name=metric_name, hours=hours)

    return AggregatedStats(**result)


@router.get("/devices/summary", response_model=list[DeviceSummary])
def get_device_summary(
    device_ids: list[int] | None = Query(None, description="Filter by device IDs"),
    hours: int = Query(24, ge=1, le=720, description="Time window in hours"),
    session: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> list[DeviceSummary]:
    """Get summary statistics for multiple devices.

    Returns overview of each device's activity including:
    - Number of distinct metrics being collected
    - Total number of readings
    - First and last reading timestamps

    Examples:
    - All devices: GET /statistics/devices/summary?hours=24
    - Specific devices: GET /statistics/devices/summary?device_ids=1&device_ids=2
    """
    service = StatisticsService(session)
    results = service.get_multi_device_summary(device_ids=device_ids, hours=hours)

    return [DeviceSummary(**result) for result in results]


@router.get("/distribution/{device_id}/{metric_name}", response_model=MetricDistribution)
def get_metric_distribution(
    device_id: int,
    metric_name: str,
    hours: int = Query(24, ge=1, le=720, description="Time window in hours"),
    buckets: int = Query(10, ge=5, le=50, description="Number of histogram buckets"),
    session: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> MetricDistribution:
    """Get value distribution (histogram) for a metric.

    Returns histogram showing how metric values are distributed.
    Useful for understanding value ranges and detecting patterns.

    Example: GET /statistics/distribution/1/temperature?hours=24&buckets=10
    """
    service = StatisticsService(session)
    result = service.get_metric_distribution(
        device_id=device_id, metric_name=metric_name, hours=hours, bucket_count=buckets
    )

    return MetricDistribution(**result)
